package com.chatplus.application.common.lock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class TurnRightLock {

    private final RedissonClient redissonClient;

    public TurnRightLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 申请锁，若锁已被占用，则返回null
     */
    public TLock tryLock(String key) {
        long defaultLockAtLeast = 5;
        return tryLock(key, defaultLockAtLeast);
    }

    /**
     * 申请锁，若锁已被占用，则返回null
     */
    public TLock tryLock(String key, long lockAtLeastInSeconds) {
        RLock lock = redissonClient.getLock(key);
        try {
            boolean getLock = lock.tryLock(0, lockAtLeastInSeconds, TimeUnit.SECONDS);
            return getLock ? new TLock(lock) : null;
        } catch (InterruptedException e) {
            return null;
        }
    }

}
